package com.youyi.threadPool;

/**
 * 自定义线程池实现
 * @author youyi.time
 * @date 2024/11/22 23:02
 */
import java.util.concurrent.*;

public class CustomThreadPool {

    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4)); // 合理的默认值
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final long KEEP_ALIVE_TIME = 60L;

    private ThreadPoolExecutor executor;

    public CustomThreadPool() {
        executor = new ThreadPoolExecutor(
                CORE_POOL_SIZE,
                MAXIMUM_POOL_SIZE,
                KEEP_ALIVE_TIME,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1024),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );

        // 定时调整线程池大小
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(this::adjustPoolSize, 0, 10, TimeUnit.SECONDS);
    }


    public CustomThreadPool(int corePoolSize,
                            int maximumPoolSize,
                            long keepAliveTime,
                            TimeUnit unit,
                            BlockingQueue<Runnable> workQueue,
                            ThreadFactory threadFactory,
                            RejectedExecutionHandler handler){
        executor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
    }

    private void adjustPoolSize() {
        int activeCount = executor.getActiveCount();
        int queueSize = executor.getQueue().size();
        int corePoolSize = executor.getCorePoolSize();

        if (activeCount + queueSize > corePoolSize) {
            // 如果活动线程加上队列中的任务数量超过了核心线程数，则增加核心线程数
            int newCorePoolSize = Math.min(corePoolSize + 1, MAXIMUM_POOL_SIZE);
            executor.setCorePoolSize(newCorePoolSize);
        } else if (activeCount < corePoolSize * 0.75) {
            // 如果活动线程少于核心线程数的75%，则减少核心线程数
            int newCorePoolSize = Math.max(corePoolSize - 1, CORE_POOL_SIZE);
            executor.setCorePoolSize(newCorePoolSize);
        }
    }

    public void execute(Runnable task) {
        executor.execute(task);
    }

    public void shutdown() {
        executor.shutdown();
    }

    public static void main(String[] args) {
        CustomThreadPool dynamicThreadPool = new CustomThreadPool();
        for (int i = 0; i < 100; i++) {
            final int taskId = i;
            dynamicThreadPool.execute(() -> {
                System.out.println("Task " + taskId + " is running by " + Thread.currentThread().getName());
                try {
                    Thread.sleep(1000); // 模拟任务执行
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        dynamicThreadPool.shutdown();
    }
}